'use strict';

const Controller = require('egg').Controller;
const { ObjectId } = require("mongodb");

class CollectController extends Controller {
    async index() {
        const { ctx } = this;
        var { id, collected } = ctx.request.body;
        collected = (collected == "true") ? true : false;
        const db = this.app.mongodb;
        const tables = ["top250", "inTheaters", "comingSoon"];
        for (var i = 0; i < tables.length; i++) {
            await db.collection(tables[i]).updateOne({ _id: id }, { $set: { collected } });
            var res = await db.collection(tables[i]).find({ _id: id }).toArray();
            if (res.length) {
                res[0]._id = ObjectId(res[0]._id);
                try {
                    if (collected) {
                        await db.collection("user").insertOne(res[0])
                        ctx.body = {
                            status: 200,
                            msg: "收藏成功"
                        }
                    } else {
                        await db.collection("user").deleteOne({ _id: ObjectId(id) })
                        ctx.body = {
                            status: 200,
                            msg: "取消收藏"
                        }
                    }
                } catch (err) {
                    this.app.logger.error(err);
                    ctx.body = {
                        status: 400,
                        msg: "数据库中已经存在请不要重复添加"
                    }
                }
            }
        }
    }
}

module.exports = CollectController;
